﻿
using AutoMapper;
using D.Traceability.Domain;
using D.Traceability.ErrorCode;
using D.Traceability.Infrastructure.Infrastructure;
using D.Traceability.Write.API.APPlicant.Command;
using D.Traceability.Write.API.APPlicant.Command.BreedCommand;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace D.Traceability.Write.API.APPlicant.CommandHandler.BreedCommandHandler
{
    /// <summary>
    ///  添加养殖信息
    /// </summary>
    public class AddBreedCommandHandler : IRequestHandler<AddBreedCommand, APIResult<string>>
    {
        private readonly IBaseRepository<SU_BreedModel> baseRepository;
        private readonly IMapper mapper;

        public AddBreedCommandHandler(IBaseRepository<SU_BreedModel> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加养殖信息
        /// </summary>
        public async Task<APIResult<string>> Handle(AddBreedCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();

            //查询是否含有数据(通过 生产批次 TraceaBatch查询)
            var obj = await baseRepository.GetAll().Result.FirstOrDefaultAsync(x => x.TraceaBatch == request.TraceaBatch && x.TraceaIsDelete == false);
            //有数据执行修改操作
            if (obj != null)
            {
                obj.BreedVariety = request.BreedVariety;
                obj.BreedSource = request.BreedSource;
                obj.BreedDay = request.BreedDay;
                obj.BreedBrand = request.BreedBrand;
                obj.BreedOPeratorName = request.BreedOPeratorName;
                obj.BreedCrateTime = request.BreedCrateTime.Value.AddHours(8);
                int res = await baseRepository.Update(obj);
                if (res > 0)
                {
                    result.Code = APIEnum.设置成功;
                    result.Msg = APIEnum.设置成功.ToString();
                    result.data = res.ToString();
                }
                else
                {
                    result.Code = APIEnum.设置失败;
                    result.Msg = APIEnum.设置失败.ToString();
                    result.data = res.ToString();
                }
            }
            else
            {
                //添加操作
                var model = mapper.Map<SU_BreedModel>(request);
                int res = await baseRepository.Add(model);
                if (res > 0)
                {
                    result.Code = APIEnum.设置成功;
                    result.Msg = APIEnum.设置成功.ToString();
                    result.data = res.ToString();
                }
                else
                {
                    result.Code = APIEnum.设置失败;
                    result.Msg = APIEnum.设置失败.ToString();
                    result.data = res.ToString();
                }
            }
            return await Task.FromResult(result);
        }
    }
}
